package UDP;

import java.io.IOException;
import java.net.*;
import java.nio.file.attribute.UserPrincipal;
import java.util.Scanner;

//客户端
public class UdpEchoClient {
    private String serverIP;//服务器IP

    private int serverPort;//服务器端口号


    private DatagramSocket socket = null;

    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        //客户端不能使用固定端口号，需要操作系统随机分配
        this.socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动");

        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.print("输入要发送的内容: ");
            if (!scanner.hasNext()) {
                break;
            }

            //字符串保存请求
            String request = scanner.next();

            //创建请求
            //需要服务器的IP与端口号
            DatagramPacket requestPocket = new DatagramPacket(request.getBytes(), 0, request.getBytes().length,
                    InetAddress.getByName(serverIP), serverPort);

            //发送请求
            socket.send(requestPocket);

            //接收服务器响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);

            //将响应转化为字符串
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());

            //打印响应
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
